
var uagent    = navigator.userAgent.toLowerCase();
var is_safari = ( (uagent.indexOf('safari') != -1) || (navigator.vendor == "Apple Computer, Inc.") );
var is_ie     = ( (uagent.indexOf('msie') != -1) && (!is_opera) && (!is_safari) && (!is_webtv) );
var is_ie4    = ( (is_ie) && (uagent.indexOf("msie 4.") != -1) );
var is_moz    = (navigator.product == 'Gecko');
var is_ns     = ( (uagent.indexOf('compatible') == -1) && (uagent.indexOf('mozilla') != -1) && (!is_opera) && (!is_webtv) && (!is_safari) );
var is_ns4    = ( (is_ns) && (parseInt(navigator.appVersion) == 4) );
var is_opera  = (uagent.indexOf('opera') != -1);
var is_kon    = (uagent.indexOf('konqueror') != -1);
var is_webtv  = (uagent.indexOf('webtv') != -1);

var is_win    =  ( (uagent.indexOf("win") != -1) || (uagent.indexOf("16bit") !=- 1) );
var is_mac    = ( (uagent.indexOf("mac") != -1) || (navigator.vendor == "Apple Computer, Inc.") );
var ua_vers   = parseInt(navigator.appVersion);
	
var text_enter_url       = "Введите полный URL ссылки";
var text_enter_flash       = "Введите ссылку на флэш ролик";
var text_enter_url_name  = "Введите название сайта";
var text_enter_page_name = "Введите описание ссылки";
var text_quote          = "Использование: [QUOTE] Здесь Ваша Цитата.. [/QUOTE]";
var error_no_url        = "Вы должны ввести URL";
var error_no_title      = "Вы должны ввести название";
var error_no_email      = "Вы должны ввести e-mail адрес";
var prompt_start        = "Введите текст для форматирования";
var email_title  	    = "Введите описание ссылки (необязательно)";
var dle_prompt          = "Ввод информации";
var bb_t_emo  	        = "Вставка смайликов";
var bb_t_col  	        = "Цвет:";

var b_open = 0;
var i_open = 0;
var u_open = 0;
var s_open = 0;
var quote_open = 0;
var code_open = 0;
var sql_open = 0;
var html_open = 0;
var left_open = 0;
var center_open = 0;
var right_open = 0;
var hide_open = 0;
var color_open = 0;
var spoiler_open = 0;
var ie_range_cache = '';

var iChatField  = "message";

var iChatiChatBBtags   = new Array();

var iChatForm    = document.iChat_form;

function stacksize(thearray)
{
	for (i = 0 ; i < thearray.length; i++ )
	{
		if ( (thearray[i] == "") || (thearray[i] == null) || (thearray == 'undefined') )
		{
			return i;
		}
	}
	
	return thearray.length;
}

function iChatpushstack(thearray, newval)
{
	arraysize = stacksize(thearray);
	thearray[arraysize] = newval;
}

function iChatpopstack(thearray)
{
	arraysize = stacksize(thearray);
	theval = thearray[arraysize - 1];
	delete thearray[arraysize - 1];
	return theval;
}

function iChatsetFieldName(which)
{

            if (which != iChatField)
            {
				iChatallcleartags();
                iChatField = which;

            }
}


function iChatcstat()
{
	var c = stacksize(iChatBBtags);
	
	if ( (c < 1) || (c == null) ) {
		c = 0;
	}
	
	if ( ! iChatBBtags[0] ) {
		c = 0;
	}
	

}


function iChatcloseall()
{
	if (iChatBBtags[0])
	{
		while (iChatBBtags[0])
		{
			tagRemove = iChatpopstack(iChatBBtags)
			var closetags = "[/" + tagRemove + "]";

			eval ("iChatForm." +iChatField+ ".value += closetags");
			
			if ( (tagRemove != 'font') && (tagRemove != 'size') )
			{
				eval(tagRemove + "_open = 0");
				document.getElementById( 'b_' + tagRemove ).className = 'editor_button';

			}
		}
	}

	iChatBBtags = new Array();

}

function iChatallcleartags()
{
	if (iChatBBtags[0])
	{
		while (iChatBBtags[0])
		{
			tagRemove = iChatpopstack(iChatBBtags)
			
				eval(tagRemove + "_open = 0");
				document.getElementById( 'b_' + tagRemove ).className = 'editor_button';

		}
	}

	iChatBBtags = new Array();

}

function emoticon(theSmilie)
{
	iChatInsert(" " + theSmilie + " ", "", false);
}


function iChat_otvet(name)
{
	iChatInsert("[b]" + name + "[/b],", "", false);
}


function add_code(NewCode)
{
    iChatForm.iChatField.value += NewCode;
    iChatForm.iChatField.focus();
}

function iChat_tag(thetag)
{
	var tagOpen = eval(thetag + "_open");
	

		if (tagOpen == 0)
		{
			if(iChatInsert("[" + thetag + "]", "[/" + thetag + "]", true))
			{
				eval(thetag + "_open = 1");
				document.getElementById( 'b_' + thetag ).className = 'editor_buttoncl';
				
				iChatpushstack(iChatBBtags, thetag);
				iChatcstat();

			}
		}
		else
		{
			lastindex = 0;
			
			for (i = 0 ; i < iChatBBtags.length; i++ )
			{
				if ( iChatBBtags[i] == thetag )
				{
					lastindex = i;
				}
			}
			
			while (iChatBBtags[lastindex])
			{
				tagRemove = iChatpopstack(iChatBBtags);
				iChatInsert("[/" + tagRemove + "]", "", false)


				if ( (tagRemove != 'font') && (tagRemove != 'size') )
				{
					eval(tagRemove + "_open = 0");
					document.getElementById( 'b_' + tagRemove ).className = 'editor_button';
				}
			}
			
			iChatcstat();
		}

}



function iChat_leech()
{
	var thesel = iChatget_sel(eval('iChatForm.'+ iChatField))

    if (!thesel) {
        thesel ='My Webpage';
    }

	DLEprompt(text_enter_url, "http://", dle_prompt, function (r) {

		var enterURL = r;

		DLEprompt(text_enter_url_name, thesel, dle_prompt, function (r) {

			iChatInsert("[leech="+enterURL+"]"+r+"[/leech]", "", false);
			ie_range_cache = null;
	
		});

	});
}



function iChatInsert(ibTag, ibClsTag, isSingle)
{
	var isClose = false;
	var obj_ta = eval('iChatForm.'+ iChatField);

	if ( (ua_vers >= 4) && is_ie && is_win)
	{
		if (obj_ta.isTextEdit)
		{
			obj_ta.focus();
			var sel = document.selection;
			var rng = ie_range_cache ? ie_range_cache : sel.createRange();
			rng.colapse;
			if((sel.type == "Text" || sel.type == "None") && rng != null)
			{
				if(ibClsTag != "" && rng.text.length > 0)
					ibTag += rng.text + ibClsTag;
				else if(isSingle)
					ibTag += rng.text + ibClsTag;
	
				rng.text = ibTag;
			}
		}
		else
		{
				obj_ta.value += ibTag + ibClsTag;
			
		}
		rng.select();
		ie_range_cache = null;

	}
	else if ( obj_ta.selectionEnd )
	{ 
		var ss = obj_ta.selectionStart;
		var st = obj_ta.scrollTop;
		var es = obj_ta.selectionEnd;
		
		var start  = (obj_ta.value).substring(0, ss);
		var middle = (obj_ta.value).substring(ss, es);
		var end    = (obj_ta.value).substring(es, obj_ta.textLength);
		
		if(!isSingle) middle = "";
		
		if (obj_ta.selectionEnd - obj_ta.selectionStart > 0)
		{
			middle = ibTag + middle + ibClsTag;
		}
		else
		{
			middle = ibTag + middle + ibClsTag;
		}
		
		obj_ta.value = start + middle + end;
		
		var cpos = ss + (middle.length);
		
		obj_ta.selectionStart = cpos;
		obj_ta.selectionEnd   = cpos;
		obj_ta.scrollTop      = st;


	}
	else
	{
		obj_ta.value += ibTag + ibClsTag;
	}

	obj_ta.focus();
	return isClose;
}

function iChat_color( buttonElement )
{

	if (color_open == 0) {
		document.getElementById(iChatField).focus();

		if ( is_ie )
		{
			document.getElementById(iChatField).focus();
			ie_range_cache = document.selection.createRange();
		}

		$("#cp").remove();

		$("body").append("<div id='cp' title='" + bb_t_col + "' style='display:none'><br /><iframe width=\"154\" height=\"104\" src=\"/engine/modules/iChat/template/img/bbcode/color.html\" frameborder=\"0\" marginwidth=\"0\" marginheight=\"0\" scrolling=\"no\"></iframe></div>");

		$('#cp').dialog({
			autoOpen: true,
			width: 175
		});
	}
	else
	{
			lastindex = 0;
			
			for (i = 0 ; i < iChatBBtags.length; i++ )
			{
				if ( iChatBBtags[i] == 'color' )
				{
					lastindex = i;
				}
			}
			
			while (iChatBBtags[lastindex])
			{
				tagRemove = iChatpopstack(iChatBBtags);
				iChatInsert("[/" + tagRemove + "]", "", false)
				eval(tagRemove + "_open = 0");
				document.getElementById( 'b_' + tagRemove ).className = 'editor_button';
			}
	}
}
function iChatSetColor(color)
{

		if ( iChatInsert("[color=" +color+ "]", "[/color]", true ) )
		{
			color_open = 1;
			document.getElementById( 'b_color' ).className = 'editor_buttoncl';
			iChatpushstack(iChatBBtags, "color");
		}

	$('#cp').dialog("close");
    iChatcstat();
}

function iChat_emo( buttonElement )
{
		document.getElementById(iChatField).focus();

		if ( is_ie )
		{
			document.getElementById(iChatField).focus();
			ie_range_cache = document.selection.createRange();
		}

		$("#dle_emo").remove();

		$("body").append("<div id='dle_emo' title='" + bb_t_emo + "' style='display:none'>"+ document.getElementById('iChat_emos').innerHTML +"</div>");

           var w = '300';
		var h = 'auto';

		if ( $('#iChat_emos').width() >= 450 )  {$('#iChat_emos').width(450); w = '505';}
		if ( $('#iChat_emos').height() >= 300 ) { $('#iChat_emos').height(300); h = '340';}


		$('#dle_emo').dialog({
				autoOpen: true,
				show: 'slide',
				hide: 'explode',
                     	width: w,
				height: h
			});

};

function iChat_smiley ( text ){
	iChatInsert(' ' + text + ' ', '', false);

	$('#dle_emo').dialog("close");
	ie_range_cache = null;
};


function iChatget_sel(obj)
{

 if (document.selection) 
 {

   if ( is_ie )
   {
		document.getElementById(iChatField).focus();
		ie_range_cache = document.selection.createRange();
   }

   var s = document.selection.createRange(); 
   if (s.text)
   {
	 return s.text;
   }
 }
 else if (typeof(obj.selectionStart)=="number")
 {
   if (obj.selectionStart!=obj.selectionEnd)
   {
     var start = obj.selectionStart;
     var end = obj.selectionEnd;
	 return (obj.value.substr(start,end-start));
   }
 }

 return false;

};